package demo;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-03-31
 * Time: 10:48
 */
public class Mystack {
    public int[] array;
    public int usedSize;

    public Mystack() {
        array = new int[10];
    }

    public void push(int val) {
        //判断是否需要扩容
        if(ifFull()) {
            array = Arrays.copyOf(array,array.length*2);
        }
        array[usedSize] = val;
        usedSize++;
    }

    private boolean ifFull() {
        return this.usedSize == array.length;
    }


    public int pop() {
        //判断是否有数据
        if(empty()) {
            try {
                checkPopandPeek();
            }catch (Empty empty) {
                empty.printStackTrace();
            }
        }
        int oldVal = array[usedSize - 1];
        usedSize--;
        //如果为引用数据类型：array[usedSize] = null;
        return oldVal;
    }
    private void checkPopandPeek() throws Empty{
        throw new Empty("没有数据可以出栈!");
    }

    private boolean empty() {
        return this.usedSize == 0;
    }

    public int peek() {
        if(empty()) {
            try {
                checkPopandPeek();
            }catch (Empty empty) {
                empty.printStackTrace();
            }
        }
        return array[usedSize-1];
    }


}
